﻿using AutojsController.Config;
using AutojsController.Helpers;
using AutojsController.Services;
using Avalonia;
using Avalonia.Threading;
using ReactiveUI;
using Serilog;
using SukiUI.Dialogs;
using SukiUI.Toasts;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;

namespace AutojsController.ViewModels
{
    public class MobileViewModel: ViewModelBase
    {
        private readonly ISukiDialogManager dialogManager;
        private readonly ISukiToastManager toastManager;
        private readonly MobilesService mobservice;
        public ObservableCollection<MobileItemViewModel> Mobiles { get; }
        public ICommand ShowScanDialog => ReactiveCommand.Create(showScanDialog);
        public ICommand ShowAddDialog => ReactiveCommand.Create(showAddDialog);
        public ICommand BatchDelete => ReactiveCommand.CreateFromTask(deleteMobiles);
        public ICommand BatchConnect => ReactiveCommand.CreateFromTask(connectMobiles);
        private readonly ILogger logger = LoggerFactory.GetLogger();

        public MobileViewModel(ISukiDialogManager dialogManager, ISukiToastManager toastManager, MobilesService mobservice) : base("手机管理", Material.Icons.MaterialIconKind.MobilePhone, 1)
        {
            this.dialogManager = dialogManager;
            this.toastManager = toastManager;
            this.mobservice = mobservice;
            this.Mobiles = mobservice.MobileItems;
            mobservice.MobileItems.CollectionChanged += (s, e) => 
            {
                this.RaisePropertyChanged(nameof(Mobiles));
            };
        }
        
        public void SelectMobileOrNot(MobileItemViewModel mobile)
        {
            mobile.IsSelected = !mobile.IsSelected;
        }

        private void showScanDialog()
        {
            dialogManager.CreateDialog().ShowCardBackground(true)
                .WithViewModel(dialog => new ScanMobilesDialogViewModel(dialog, toastManager, mobservice))
                .TryShow();
        }

        private void showAddDialog()
        {
            dialogManager.CreateDialog().ShowCardBackground(true)
                .WithViewModel(dialog => new AddMobileDialogViewModel(dialog, toastManager, mobservice))
                .TryShow();
        }

        private async Task connectMobiles()
        {
            await Parallel.ForEachAsync(Mobiles.Where(m => m.IsSelected),
                                        new ParallelOptions { MaxDegreeOfParallelism = Consts.PARALLEL_CONCURRENT_COUNT },
                                        async (mobile, ct) =>{ await mobile.ConnectAction(); });
        }

        private async Task deleteMobiles()
        {
            await Parallel.ForEachAsync(Mobiles.Where(m => m.IsSelected), async (mobile, ct) =>
            {
                try
                {
                    logger.Information($"删除设备:{mobile.Mobile.Address}");
                    await mobservice.SafeDeleteMobileAsync(mobile.Mobile.Id);
                }
                catch (Exception e)
                {
                    logger.Error(e, $"删除设备:{mobile.Mobile.Address}失败");
                    Dispatcher.UIThread.Invoke(() =>
                    {
                        SukiToast.Error(toastManager, $"删除{mobile.Mobile.Address}失败: {e.Message}", 3);
                    });
                }
            });
        }
    }
}
